<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <el-tabs v-model="activeTab" tabPosition="left">
        <!-- 个人信息 -->
        <el-tab-pane label="个人信息" name="info">
          <el-form ref="formRef" :model="userForm" :rules="rules" label-width="100px">
            <el-form-item label="用户名">
              <el-input v-model="userForm.username" disabled />
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="userForm.nickname" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdateInfo" :loading="loading">
                保存修改
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 预约管理 -->
        <el-tab-pane label="预约管理" name="appointments">
          <el-table :data="appointments" style="width: 100%">
            <el-table-column prop="date" label="预约日期" />
            <el-table-column prop="photographer" label="摄影师" />
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-tag :type="row.status === 'pending' ? 'warning' : 'success'">
                  {{ row.status === 'pending' ? '待确认' : '已确认' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button
                  type="danger"
                  size="small"
                  @click="handleCancelAppointment(row.id)"
                  v-if="row.status === 'pending'"
                >
                  取消预约
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 订单管理 -->
        <el-tab-pane label="订单管理" name="orders">
          <el-table :data="orders" style="width: 100%">
            <el-table-column prop="orderNo" label="订单编号" />
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column prop="amount" label="金额" />
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-tag :type="getOrderStatusType(row.status)">
                  {{ getOrderStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleViewOrder(row.id)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getUserInfo, updateUserInfo } from '@/api/user'
import { useUserStore } from '@/stores/user'
import type { UpdateUserRequest, UserInfo } from '@/types/user'
import Logger from '@/utils/logger'

const activeTab = ref('info')
const userStore = useUserStore()
const loading = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const userForm = reactive<UserInfo>({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  id: 0,
})

// 表单验证规则
const rules = reactive<FormRules>({
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
})

// 模拟数据
const appointments = ref([
  { id: 1, date: '2024-03-20', photographer: '张摄影', status: 'pending' },
  { id: 2, date: '2024-03-25', photographer: '李摄影', status: 'confirmed' },
])

const orders = ref([
  {
    id: 1,
    orderNo: 'ORD20240315001',
    createTime: '2024-03-15',
    amount: '2999',
    status: 'paid',
  },
])

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    Logger.info('开始获取用户信息')
    const { data } = await getUserInfo()
    Object.assign(userForm, data.data)
    userStore.updateUserDetails(data.data)
    Logger.info('用户信息获取成功')
  } catch (error) {
    Logger.error('获取用户信息失败', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 更新用户信息
const handleUpdateInfo = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        Logger.info('开始更新用户信息', userForm)
        const formData: UpdateUserRequest = {
          nickname: userForm.nickname,
          email: userForm.email,
          phone: userForm.phone,
        }
        const { data } = await updateUserInfo(formData)
        userStore.updateUserDetails(data.data)
        ElMessage.success('用户信息更新成功')
        Logger.info('用户信息更新成功')
      } catch (error) {
        Logger.error('更新用户信息失败', error)
        ElMessage.error('用户信息更新失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 订单状态
const getOrderStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    unpaid: 'warning',
    paid: 'success',
    completed: 'info',
    cancelled: 'danger',
  }
  return statusMap[status] || 'info'
}

const getOrderStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    unpaid: '待支付',
    paid: '已支付',
    completed: '已完成',
    cancelled: '已取消',
  }
  return statusMap[status] || status
}

// 取消预约
const handleCancelAppointment = async (id: number) => {
  // TODO: 实现取消预约逻辑
  ElMessage.success('预约已取消')
}

// 查看订单详情
const handleViewOrder = (id: number) => {
  // TODO: 实现查看订单详情逻辑
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  min-height: calc(100vh - 200px);
  box-sizing: border-box;
}

.profile-card {
  margin-top: 20px;
}
</style>
